// Next.js API route support: https://nextjs.org/docs/api-routes/introduction
import type {NextApiRequest, NextApiResponse} from 'next'

const crypto = require('crypto');

type Data = {
  encryptArray: any[]
}

export default function handler(
  req: NextApiRequest,
  res: NextApiResponse<Data | {}>
) {
  const requestBody = req.body;
  if (!requestBody.publicKey || !Array.isArray(requestBody.data)) {
    res.status(401).json({});
  }
  const processArray = requestBody.data || [];
  const encryptArray = processArray.map(item => {
    let value;
    try{
      value = crypto.publicEncrypt(requestBody.publicKey, Buffer.from(item.value)).toString('base64') || item.value;
    } catch (error) {
      console.log('encrypt error', item.value);
      value = item.value;
    }


    return {recordId: item.recordId, value: value}
  });
  res.status(200).json({encryptArray})
}
